from io import BytesIO
from operator import or_

from flask import Blueprint, jsonify, make_response
from flask_restful import Api,Resource,reqparse,marshal
from common.utils.my_output_json import custom_uotput_json
from common.captcha import Captcha

user_bp = Blueprint('user_bp',__name__,url_prefix='/users')

api = Api(user_bp)
from models import db
import random,redis
from tasks.sms.task import sms_code
#统一后端返回给前端的数据结构
@api.representation('application/json')
def output_json(data, code, headers=None):
    resp = custom_uotput_json(data, code)
    return resp
class SendSmsCode(Resource):
    def get(self):
        parser = reqparse.RequestParser()
        parser .add_argument('phone')
        args = parser.parse_args()
        mobile = args.get('phone')
        code = random.randint(1000,9999)
        print('code',code)
        rest = sms_code.delay(code,mobile)
        if rest:
            rds = redis.Redis()
            rds.set(mobile,code)
            return jsonify(message='验证码发送成功',code=200)
        else:
            return jsonify(message='验证码发送失败',code=500)
api.add_resource(SendSmsCode,'/smscode')


from werkzeug.security import generate_password_hash,check_password_hash
from models.user import User
# 注册
class UserRegister(Resource):
    def post(self):
        parser = reqparse.RequestParser()
        parser.add_argument('username')
        parser.add_argument('password')
        parser.add_argument('phone')
        parser.add_argument('password2')
        parser.add_argument('code')
        args = parser.parse_args()
        name = args.get('username')
        password = args.get('password')
        pwd = generate_password_hash(password)
        mobile = args.get('phone')
        affirm = args.get('password2')
        code = args.get('code')
        print('1111111111111',name,password,mobile,affirm)
        users = User.query.filter_by(account=name).first()
        if users:
            return jsonify(message='用户已经存在',cdeo=500)
        if password != affirm:
            return jsonify(message='两次密码不正确',code=500)
        if not all([name,password,mobile]):
            return jsonify(message='请完善信息',code=500)
        rds = redis.Redis()
        sms_code = rds.get(mobile)
        if sms_code.decode() == code:
            try:
                user = User(account=name,password=pwd,mobile=mobile)
                print("user",user)
                db.session.add(user)
                db.session.commit()
                return jsonify(message='注册成功',code=200)
            except Exception as e:
                print('错误',e)
                return jsonify(message='注册失败',code=500)
        else:
            return jsonify(message='验证码错误',code=500)




        
api.add_resource(UserRegister,'/register')

# 图片验证码
import  string

class Picture(Resource):
    def get(self):
        parser = reqparse.RequestParser()
        parser.add_argument('uuid')
        args = parser.parse_args()
        uuid = args.get('uuid')
        print('uuid>>>>', uuid)
        text, image = Captcha.gene_graph_captcha()
        out = BytesIO()
        image.save(out, 'png')
        out.seek(0)
        resp = make_response(out.read())
        resp.content_type = 'image/png'
        return resp
api.add_resource(Picture,'/code')

#登录
from common.jwt_token import gen_toen
class Login(Resource):
    def post(self):
        parser = reqparse.RequestParser()
        parser.add_argument('uuid')
        parser.add_argument('account')
        parser.add_argument('password')
        parser.add_argument('img_code')
        args = parser.parse_args()
        username = args.get('account')
        password = args.get('password')
        img_code = args.get('img_code')
        uuid = args.get('uuid')
        print(username, password, img_code, uuid)
        if not all([username, password, img_code, uuid]):
            return jsonify(message="请补全登录信息", code=400)
        user = User.query.filter(or_(User.account == username, User.mobile == username)).first()
        if not user:
            return jsonify(message="用户不存在", code=400)
        if not check_password_hash(user.password, password):
            return jsonify(message="密码错误", code=400)
        rds = redis.Redis()
        code = rds.get(uuid)
        if code and code.decode().lower() != img_code.lower:
            return jsonify(message="验证码错误或过期", code=400)
        data = {
            'uid':user.uid,
            'username':user.account
        }
        token = gen_toen(data)
        return jsonify(message='登录成功',code=200,token=token,data=data)

api.add_resource(Login,'/login')

from common.jwt_token import check_token
from common.models_fields import *
#修改  获取 用户信息
class UpdateUser(Resource):
    def get(self):
        parser = reqparse.RequestParser()
        parser.add_argument('token')
        args = parser.parse_args()
        token = args.get('token')
        if  token:
            payload = check_token(token)
            id = payload['uid']
            user_info = User.query.filter_by(uid=id).first()
            if not user_info:
                return jsonify(message='用户不存在',code=400)
            data = marshal(user_info,user_fields)
            return jsonify(code=200,data=data)
        else:
            return jsonify(message='请先登录',code=204)

    def post(self):
        parser = reqparse.RequestParser()
        parser.add_argument('token')
        parser.add_argument('username')
        parser.add_argument('occupation')
        parser.add_argument('school')
        parser.add_argument('img')
        args = parser.parse_args()
        token = args.get('token')
        username = args.get('username')
        occupation = args.get('occupation')
        school = args.get('school')
        img = args.get('img')
        if not all([username,occupation,school,img]):
            return jsonify(message='信息不完整',code=204)
        if token:
            payload = check_token(token)
            id = payload['uid']
            user_info = User.query.filter_by(uid=id).first()
            if not user_info:
                return jsonify(message='用户不存在', code=400)
            else:
                try:
                    User.query.filter_by(uid=id).update(
                        {'account': username, 'occupation': occupation, 'school': school, 'profile_photo': img})
                    db.session.commit()  # 保存
                    return jsonify(message='修改成功', code=200)
                except Exception as e:
                    print("eeeeeee",e)
                    return jsonify(message='修改失败',code=500)
        else:
            return jsonify(message='请先登录', code=204)
api.add_resource(UpdateUser,'/user_info')